package com.ip;

import org.jetbrains.annotations.NotNull;

import java.util.Scanner;

public class IPUtility {
    static Scanner scanner = new Scanner(System.in);

    public static String getInitIpAdress() {
        Scanner scanner = new Scanner(System.in);
        String ipAdress;
        System.out.println("Introduceti adresa IP:");
        ipAdress = scanner.nextLine();
        return ipAdress;
    }

    public static int getCalcNumber() {
        int nr;
        System.out.print("Introduceti numarul de calculatoare : ");
        nr = scanner.nextInt();
        return nr;
    }

    static int nextPowerOfTwo(final int nrOfCalc) {
        int i = 0;
        int number = nrOfCalc + 2;
        if (number > 0 && (number & (number - 2)) == 0)
            return number;
        while (number != 0) {
            number >>= 1;
            i += 1;
        }
        return 1 << i;
    }

    public static void printMask(final int exp) {
        int[] mask = new int[32];
        for (int i = 0; i < mask.length; i++) {
            mask[i] = 0;
            for (int j = 0; j < mask.length - exp; j++) {
                mask[j] = 1;
            }
        }
        System.out.println("Masca este : ");
        for (int i = 0; i < mask.length; i++) {
            if (i == 8 || i == 16 || i == 24) {
                System.out.print(" ");
                System.out.print(mask[i]);
            } else
                System.out.print(mask[i]);
        }
        System.out.println("\n");
    }

    public static int[] ipAdressParserToInt(@NotNull final String ip) {
        final String REGEX = "\\.";
        int i = 0;
        int[] ipAdress = new int[4];
        String[] valueOfIp = ip.split(REGEX);
        for (String s : valueOfIp) {
            ipAdress[i] = Integer.parseInt(s);
            i++;
        }
        return ipAdress;
    }

    public static void printIpAdresses(@NotNull final int[] parsedIp, final int nrCalc, final int nextPowOfTwo) {
        final int maxB = 255;
        int c = parsedIp[2];
        int fullListOfAdresses = nrCalc + 1;
        int adressCounter = 0;
        for (int i = 0; i <= fullListOfAdresses; i++) {
            if (adressCounter <= nextPowOfTwo) {
                if (i == 0) {
                    System.out.println(parsedIp[0] + "." + parsedIp[1] + "." + c + "." + i + "\t- Router reserved");
                } else
                    System.out.println(parsedIp[0] + "." + parsedIp[1] + "." + c + "." + i);
                if (i == maxB) {
                    i = 0;
                    c++;
                }
                if (adressCounter == fullListOfAdresses) {
                    break;
                }
                adressCounter++;
            } else System.out.println("error !!!!");
        }
        System.out.println(parsedIp[0] + "." + parsedIp[1] + "." + c + "." + (nextPowOfTwo - 1) + "\t- BROADCAST");
        System.out.println("Numarul maxim de adrese disponibile cu masca data : " + nextPowOfTwo);
    }
}
